package com.xingdata.jjxc.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Date;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;

/**
 * SD卡管理工具*项目名称： com.newtouch.crm1_2 包名： com.newtouch.crm1_2.utility 类名称:
 * SDCardTools.java 创建人：JiangMin 创建时间： 2014-7-26 下午5:44:59 修改人：JiangMin
 * 修改时间：2014-7-26 下午5:44:59
 */
public class SDCardTools {
	private static String TAG = "SDCardTools";
	private static boolean LocalImagesucceed = true;
	// 有效SD卡内存大小
	private static final long SD_MIN_AVAILALE = 100;
	/**
	 * 用于保存客户端临时文件的目录
	 */
	public static final String COMPANY_NAME = "jjxc/";
	/**
	 * 用于保存图片文件的目录
	 */
	public static final String PRODUCTS_IMAGE_NAME = "Image";
	/**
	 * 用于保存录音文件的目录
	 */
	public static final String RECORD_NAME = "Record";
	/**
	 * 用于保存视频文件的目录
	 */
	public static final String VIDEO_NAME = "Video";
	/**
	 * 用于保存离线地图数据
	 */
	public static final String OFFLINE_MAP = "amapsdk";
	/**
	 * 用于保存错误日志
	 */
	private static String CRASH_NAME = "Crash";
	/**
	 * 系统升级包
	 */
	public static String UPGRADEDATA_NAME = "data";

	/**
	 * 判断SD卡是否存在并且SD卡正常挂载
	 * 
	 * @return 存在返回true
	 */
	public static boolean isSDcardExist() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			return true;
		}
		return false;
	}

	public static boolean isSDcard() {
		boolean isSDcard = false;
		if (isSDcardExist()) {
			isSDcard = true;
		}
		return isSDcard;
	}

	/**
	 * 计算SD剩下空间大小
	 * 
	 * @return MB
	 */
	public static long getSDAvailaleSize() {
		if (isSDcard()) {
			// 取得sdcard文件路径
			File path = Environment.getExternalStorageDirectory();
			StatFs statfs = new StatFs(path.getPath());
			// 获取SDCard上BLOCK总数
			long nTotalBlocks = statfs.getBlockCount();

			// 获取SDCard上每个block的SIZE
			long nBlocSize = statfs.getBlockSize();

			// 获取可供程序使用的Block的数量
			long nAvailaBlock = statfs.getAvailableBlocks();

			// 获取剩下的所有Block的数量(包括预留的一般程序无法使用的块)
			long nFreeBlock = statfs.getFreeBlocks();

			// 计算SDCard 总容量大小MB 目前没用到
			// long nSDTotalSize = nTotalBlocks * nBlocSize / 1024 / 1024;

			// 计算 SDCard 剩余大小MB
			long nSDFreeSize = nAvailaBlock * nBlocSize / 1024 / 1024;
			return nSDFreeSize;
		}
		return 0;
	}

	/**
	 * 根据URL删除SD卡上面的图片
	 * 
	 * @param filePath
	 * @param fileName
	 */
	public static void deleteImage(String fileName) {
		String mFilePath = isCacheFileIsExit(PRODUCTS_IMAGE_NAME);
		if (fileName != null) {
			File file = new File(mFilePath + "/" + fileName);
			Log.i(TAG, "the file : " + file);
			if (file.exists() && !file.isDirectory()) {
				Log.i(TAG, "the image " + fileName + " haved delete");
				try {
					file.delete();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 判断当前文件是否存在如果不存在新建当前文件夹
	 */
	public static String isCacheFileIsExit(String path) {
		String filePath = "";
		if (isSDcard() == true) {
			filePath = getFilePath(path);
		}
		return filePath;
	}

	/**
	 * 判断当前SD卡空间是否足够（必须大于100MB）
	 * 
	 * @return
	 */
	public static boolean isAvailaleDir() {
		if (getSDAvailaleSize() < SD_MIN_AVAILALE) {
			Log.e(TAG, "当前SD卡的目录" + getSDAvailaleSize());
			return false;
		}

		return true;
	}

	public static boolean clearCache() {
		String rootpath = Environment.getExternalStorageDirectory().toString();
		String filePath = rootpath + "/jjxc";
		File file = new File(filePath);
		if (!file.exists()) {

			return true;
		}
		return delAllFile(filePath);

	}

	/**
	 * 清理缓存
	 * 
	 * @param file
	 */
	public static void clearFile(File file) {
		File[] flist = null;
		flist = file.listFiles();
		if (flist != null) {
			for (int i = 0; i < flist.length; i++) {
				if (flist[i].isDirectory()) {
					clearFile(flist[i]);
				} else {
					flist[i].delete();
				}
			}
		}
		Log.i(TAG, "after claer this file size:" + file.length());
	}

	/**
	 * 当Activity退出的时候回收所有图片
	 * 
	 * @param ArrayListBitmap
	 */
	public static void onDestroy(ArrayList<Bitmap> ArrayListBitmap) {
		if (null != ArrayListBitmap) {
			for (int i = 0; i < ArrayListBitmap.size(); i++) {
				if (ArrayListBitmap.get(i) != null
						&& !ArrayListBitmap.get(i).isRecycled()) {
					ArrayListBitmap.get(i).recycle();
				}
			}
		}
	}

	/**
	 * 根据文件目录目录新建文件夹
	 * 
	 * @param path
	 * @return
	 */
	public static String getFilePath(String path) {
		String rootpath = Environment.getExternalStorageDirectory().toString();
		String filePath = rootpath + "/" + COMPANY_NAME + path;
		File file = new File(filePath);
		if (!file.exists()) {
			file.mkdirs();
		}
		return filePath;
	}

	/**
	 * 重命名
	 * 
	 * @param fileName1
	 * @param fileName2
	 * @return
	 */
	public static boolean reName(String fileName1, String fileName2) {
		if (!StringUtil.isStringNull(fileName1)
				|| !StringUtil.isStringNull(fileName2)) {
			return false;
		}
		return new File(fileName1).renameTo(new File(fileName2));

	}

	/**
	 * 根据文件目录目录新建文件夹
	 * 
	 * @param path
	 * @return
	 */
	public static String getFileName(String path) {
		String name;
		if (path == null) {
			name = "";
		} else {
			name = path.substring(path.lastIndexOf("/") + 1);
		}
		return name;
	}

	/**
	 * 根据文件目录目录新建文件夹
	 * 
	 * @param path
	 * @return
	 */
	public static String getFilePath() {
		String rootpath = Environment.getExternalStorageDirectory().toString();
		String filePath = rootpath + "/" + COMPANY_NAME + CRASH_NAME + "/"
				+ StringUtil.ToStringData(new Date(System.currentTimeMillis()));
		File file = new File(filePath);
		if (!file.exists()) {
			file.mkdirs();
		}
		return filePath;
	}

	public static boolean delAllFile(String filePath) {
		if (filePath == null) {
			return false;
		}
		File mfile = new File(filePath);
		if (!mfile.exists()) {
			return false;
		}
		if (mfile.isFile()) {
			mfile.delete();
		} else {
			// 指定删除目录路径构造一个文件对象
			for (File file : mfile.listFiles()) {
				// 遍历删除文件
				delAllFile(file.getPath());
			}
			mfile.delete();
		}
		return true;
	}

	public static void comparisonFile() {
		String rootPath = getFilePath();
		if (rootPath == null || rootPath.indexOf("/") < 0) {
			return;
		}
		String fileName = rootPath.substring(rootPath.lastIndexOf("/") + 1,
				rootPath.length());
		String path = Environment.getExternalStorageDirectory().toString()
				+ "/" + COMPANY_NAME + CRASH_NAME;
		for (File file : new File(path).listFiles()) {
			if (!file.getName().equals(fileName)) {
				delAllFile(file.getPath());
			}
		}
	}

	/**
	 * 根据网络图片URL地址保存到本地指定文件夹目录下面
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public static Bitmap SaveUrlImage(String key, Bitmap value) {
		if (isAvailaleDir()) {
			String filePath = getFilePath(PRODUCTS_IMAGE_NAME);
			String name = ImageTools.changeImageName(key);
			if (name != null) {
				File file = new File(filePath, name);
				if (!file.exists()) {
					OutputStream outputStream = null;
					try {
						outputStream = new FileOutputStream(file);
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					}
					if (isSDcard()) {
						value.compress(CompressFormat.JPEG, 100, outputStream);
						try {
							outputStream.flush();
						} catch (IOException e) {
							e.printStackTrace();
						} finally {
							if (null != outputStream) {
								try {
									outputStream.close();
								} catch (IOException e) {
									e.printStackTrace();
								}
								outputStream = null;
							}
						}
					}

				}
				Log.i(TAG, key + ">>>>>>>>>>>>>>>>>>>>>>>   已经存在SD卡");
			} else {
				File mFile = new File(isCacheFileIsExit(PRODUCTS_IMAGE_NAME));
				clearFile(mFile);
				Log.e(TAG, "图片类型发生错误！");
			}
		} else {
			Log.e(TAG, "内存卡数据不足   请更换内存或者清除数据........");
		}
		return value;
	}

	/**
	 * 根据路径获取图片
	 * 
	 * @param url
	 * @return
	 */
	public static Bitmap getSDImage(String url,Float fMulriple) {
		String filePath = isCacheFileIsExit(PRODUCTS_IMAGE_NAME);
		String name = ImageTools.changeImageName(url);
		File mfile = new File(filePath + "/" + name);
		// 若该文件存在
		if (mfile.exists()) {
			return ImageTools
					.compressImageFromFile(filePath + "/" + name, fMulriple);
		} else {
			return null;
		}

	}

	// private static Bitmap decodeFile(String path){
	// BitmapFactory.Options bfOptions=new BitmapFactory.Options();
	// bfOptions.inDither=false;
	// bfOptions.inPurgeable=true;
	// bfOptions.inTempStorage=new byte[12 * 1024];
	// bfOptions.inJustDecodeBounds = true;
	// File file = new File(path);
	// FileInputStream fs=null;
	// Bitmap bmp = null;
	// try {
	// fs = new FileInputStream(file);
	// if(fs != null)
	// bmp = BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions);
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// return bmp;
	// }

}
